#!/usr/bin/python
# -*- coding: utf-8 -*-

######################################
#                                    #
# plugin.video.filmy-a33-pl for xbmc #
# author: t0mus                      #
#                                    #
######################################

""" Module contains common routines."""

from strings import __header_string__
from common_strings import __nextpage_string__, __networkerror_string__

import xbmcgui
import urllib2
import re
import htmlentitydefs


class TOOLS(object):
    """ Parameters handling tools."""
    def __init__(self):
        self.cmds = {}

    def load_parameters(self, params):
        """ Loads parameters."""
        self.cmds = {}
        split_cmds = params[params.find('?') + 1:].split('&')
        for cmd in split_cmds:
            if len(cmd) > 0:
                split_cmd = cmd.split('=')
                name = split_cmd[0]
                value = split_cmd[1]
                self.cmds[name] = value

    def get_cmd(self, cmd):
        """ Returns command."""
        if cmd in self.cmds:
            return self.cmds[cmd]
        else:
            return None


def unescape(text):
    """ Unescapes text."""
    def fixup(match):
        """ Fixup."""
        text = match.group(0)
        if text[:2] == '&#':

            # character reference

            try:
                if text[:3] == '&#x':
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:

            # named entity

            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text  # leave as is
    try:
        result = re.sub("&#?\w+;", fixup, text)
    except:
        result = 'error'
    return result


def write_url_to_file(url, file_path):
    """ Writes url to file."""

    new_file = open(file_path,'w+')
    new_file.write(open_url(url).read())
    new_file.close()


def open_url(url):
    """ Opens url using urllib2."""

    try:
        request = urllib2.Request(url)
        request.add_header('Referer',url)
        return urllib2.urlopen(request)
    except IOError:
        xbmcgui.Dialog().ok(__header_string__, __networkerror_string__)


def create_next_page_list_item(page, count, step):
    """ Creates next page list item."""
    return xbmcgui.ListItem(__nextpage_string__ + ' (' + str(page * step
                            + 1) + ' - ' + str(page * step + count)
                            + ')')


